#include "SolitaireScene.h"

SolitaireScene* SolitaireScene::create() {
    CCLOG("[SolitaireScene] create() called");
    auto scene = new (std::nothrow) SolitaireScene();
    CCLOG("[SolitaireScene] Scene object created: %p", scene);
    if (scene && scene->init()) {
        CCLOG("[SolitaireScene] Scene initialized, calling autorelease()");
        scene->autorelease();
        CCLOG("[SolitaireScene] autorelease() completed");
        return scene;
    }
    CCLOG("[SolitaireScene] Init failed, deleting scene");
    delete scene;
    return nullptr;
}

bool SolitaireScene::init() {
    CCLOG("[SolitaireScene] init() called");

    CCLOG("[SolitaireScene] Calling Scene::init()...");
    if (!Scene::init()) {
        CCLOG("[SolitaireScene] Scene::init() failed!");
        return false;
    }
    CCLOG("[SolitaireScene] Scene::init() succeeded");

    m_draggedCard = nullptr;

    // 创建场景内容
    CCLOG("[SolitaireScene] Creating background...");
    createBackground();
    CCLOG("[SolitaireScene] Creating title...");
    createTitle();
    CCLOG("[SolitaireScene] Creating demo cards...");
    createDemoCards();
    CCLOG("[SolitaireScene] Setting up touch listener...");
    setupTouchListener();

    CCLOG("[SolitaireScene] Scene initialized");

    return true;
}

void SolitaireScene::createBackground() {
    // 创建绿色背景（经典纸牌桌面颜色）
    auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
    auto origin = cocos2d::Director::getInstance()->getVisibleOrigin();

    auto background = cocos2d::LayerColor::create(cocos2d::Color4B(34, 139, 34, 255));  // 森林绿
    addChild(background, -1);

    CCLOG("[SolitaireScene] Background created: %.0fx%.0f", visibleSize.width, visibleSize.height);
}

void SolitaireScene::createTitle() {
    auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
    auto origin = cocos2d::Director::getInstance()->getVisibleOrigin();

    // 标题文字
    auto title = cocos2d::Label::createWithSystemFont(
        "Solitaire Demo - Qt + cocos2d-x",
        "Arial",
        48
    );
    title->setPosition(cocos2d::Vec2(
        origin.x + visibleSize.width / 2,
        origin.y + visibleSize.height - 50
    ));
    title->setColor(cocos2d::Color3B::WHITE);
    title->enableOutline(cocos2d::Color4B::BLACK, 2);  // 描边
    addChild(title, 10);

    // 说明文字
    auto hint = cocos2d::Label::createWithSystemFont(
        "Click and drag the cards below\n(This is a demo - full game logic can be added)",
        "Arial",
        20
    );
    hint->setPosition(cocos2d::Vec2(
        origin.x + visibleSize.width / 2,
        origin.y + visibleSize.height - 120
    ));
    hint->setColor(cocos2d::Color3B::WHITE);
    hint->setAlignment(cocos2d::TextHAlignment::CENTER);
    addChild(hint, 10);

    CCLOG("[SolitaireScene] Title created");
}

void SolitaireScene::createDemoCards() {
    auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize();
    auto origin = cocos2d::Director::getInstance()->getVisibleOrigin();

    float centerX = origin.x + visibleSize.width / 2;
    float centerY = origin.y + visibleSize.height / 2;

    // 创建一些演示卡牌（模拟不同花色）
    // 红桃 (Hearts) - 红色
    auto heartCard = createCard(centerX - 250, centerY, cocos2d::Color4B::RED, "A♥");
    addChild(heartCard, 1);

    // 方块 (Diamonds) - 红色
    auto diamondCard = createCard(centerX - 100, centerY, cocos2d::Color4B(255, 100, 100, 255), "K♦");
    addChild(diamondCard, 1);

    // 黑桃 (Spades) - 黑色
    auto spadeCard = createCard(centerX + 50, centerY, cocos2d::Color4B(50, 50, 50, 255), "Q♠");
    addChild(spadeCard, 1);

    // 梅花 (Clubs) - 黑色
    auto clubCard = createCard(centerX + 200, centerY, cocos2d::Color4B(80, 80, 80, 255), "J♣");
    addChild(clubCard, 1);

    CCLOG("[SolitaireScene] Demo cards created");
}

cocos2d::Node* SolitaireScene::createCard(float x, float y, const cocos2d::Color4B& color, const std::string& label) {
    // 卡牌尺寸（标准纸牌比例约2:3）
    const float CARD_WIDTH = 100;
    const float CARD_HEIGHT = 150;

    // 创建卡牌容器
    auto card = cocos2d::Node::create();
    card->setPosition(cocos2d::Vec2(x, y));
    card->setContentSize(cocos2d::Size(CARD_WIDTH, CARD_HEIGHT));

    // 卡牌背景（圆角矩形）
    auto cardBg = cocos2d::DrawNode::create();
    cocos2d::Vec2 vertices[4] = {
        cocos2d::Vec2(0, 0),
        cocos2d::Vec2(CARD_WIDTH, 0),
        cocos2d::Vec2(CARD_WIDTH, CARD_HEIGHT),
        cocos2d::Vec2(0, CARD_HEIGHT)
    };
    // 将Color4B转换为Color4F
    cocos2d::Color4F colorF(color.r / 255.0f, color.g / 255.0f, color.b / 255.0f, color.a / 255.0f);
    cardBg->drawSolidPoly(vertices, 4, colorF);
    card->addChild(cardBg, 0);

    // 白色边框
    auto border = cocos2d::DrawNode::create();
    border->drawRect(
        cocos2d::Vec2(2, 2),
        cocos2d::Vec2(CARD_WIDTH - 2, CARD_HEIGHT - 2),
        cocos2d::Color4F::WHITE
    );
    card->addChild(border, 1);

    // 卡牌标签（花色和点数）
    auto labelNode = cocos2d::Label::createWithSystemFont(label, "Arial", 36);
    labelNode->setPosition(cocos2d::Vec2(CARD_WIDTH / 2, CARD_HEIGHT / 2));
    labelNode->setColor(cocos2d::Color3B::WHITE);
    labelNode->enableOutline(cocos2d::Color4B::BLACK, 2);
    card->addChild(labelNode, 2);

    // 添加一个标识，表示这是可拖拽的卡牌
    card->setTag(1000);  // 卡牌标签

    return card;
}

void SolitaireScene::setupTouchListener() {
    auto listener = cocos2d::EventListenerTouchOneByOne::create();

    listener->onTouchBegan = CC_CALLBACK_2(SolitaireScene::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(SolitaireScene::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(SolitaireScene::onTouchEnded, this);

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

    CCLOG("[SolitaireScene] Touch listener setup");
}

bool SolitaireScene::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event) {
    auto touchPos = touch->getLocation();

    // 检查是否点击了卡牌
    auto children = getChildren();
    for (auto it = children.rbegin(); it != children.rend(); ++it) {
        auto child = *it;
        if (child->getTag() == 1000) {  // 是卡牌
            auto cardPos = child->getPosition();
            auto cardSize = child->getContentSize();

            // 简单的矩形碰撞检测
            cocos2d::Rect cardRect(
                cardPos.x - cardSize.width / 2,
                cardPos.y - cardSize.height / 2,
                cardSize.width,
                cardSize.height
            );

            if (cardRect.containsPoint(touchPos)) {
                m_draggedCard = child;
                m_dragOffset = cardPos - touchPos;

                // 将卡牌移到最上层
                child->retain();
                child->removeFromParent();
                addChild(child, 100);
                child->release();

                CCLOG("[SolitaireScene] Card grabbed at (%.0f, %.0f)", touchPos.x, touchPos.y);
                return true;
            }
        }
    }

    return false;
}

void SolitaireScene::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event) {
    if (m_draggedCard) {
        auto touchPos = touch->getLocation();
        m_draggedCard->setPosition(touchPos + m_dragOffset);
    }
}

void SolitaireScene::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event) {
    if (m_draggedCard) {
        auto touchPos = touch->getLocation();
        CCLOG("[SolitaireScene] Card released at (%.0f, %.0f)", touchPos.x, touchPos.y);

        // 将卡牌恢复到正常层级
        m_draggedCard->setLocalZOrder(1);

        // TODO: 这里可以添加卡牌放置逻辑（检查是否合法、更新游戏状态等）

        m_draggedCard = nullptr;
    }
}
